/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package analyticsServer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.rmi.ConnectException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

/**
 *
 * @author Group 95
 */
public class Server {
    //@todo Werte aus registry.properties, nicht alles in main

    public static void main(String[] args) {

        try {
            String name;
            if (args.length ==0) {
                name = "Analytics";
            } else {
                name = args[0];
            }
            AnalyticsServer analyticsServer = new AnalyticsServer();
            Thread analyticsServerThread = new Thread(analyticsServer);
            analyticsServerThread.start();
            Registry registry = LocateRegistry.getRegistry(13249);
            try {
                registry.rebind(name, analyticsServer);
            } catch (ConnectException cex) {
                registry = LocateRegistry.createRegistry(13249);
                registry.bind(name, analyticsServer);
            }
            System.out.println("AnalyticsServer bound");
            
            //!exit
            InputStreamReader inputStream = new InputStreamReader(System.in);
            BufferedReader brStdIn = new BufferedReader(inputStream);
            String strLine;
                while ((strLine = brStdIn.readLine()) != null) {
                    if (strLine.contentEquals("!exit")) {
                        System.out.println("Exit-command entered, stop AnalyticsServer...");
                        analyticsServer.stop();
                        break;
                    }
                }
                System.out.println("AnalyticsServerStop 1");
                UnicastRemoteObject.unexportObject(analyticsServer, true);                 

                brStdIn.close();
                inputStream.close();
                System.out.println("AnalyticsServerStop 2");
        } catch (Exception e) {
            System.err.println("AnalyticsServer exception:");
            e.printStackTrace();
        }
    }
}
